package ohc.login

import com.google.gson.Gson
import com.google.gson.JsonObject
import java.net.URI
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse
import java.time.Duration
import java.util.concurrent.CompletableFuture

/**
 * 更新检测
 * 通过读取仓库中的 version.json 检测更新
 */
object UpdateChecker {
    private val httpClient: HttpClient = HttpClient.newBuilder()
        .connectTimeout(Duration.ofSeconds(10))
        .build()
    private val gson = Gson()
    
    // version.json 的 raw 链接
    private const val VERSION_URL = "https://raw.gitcode.com/STCaoMei/ohc_login/raw/main/version.json"
    private const val MC_VERSION = "1.21.10"
    
    const val CURRENT_VERSION = "1.0.0"
    
    @Volatile
    var cachedUpdateInfo: UpdateInfo? = null
        private set
    
    data class UpdateInfo(
        val hasUpdate: Boolean,
        val currentVersion: String,
        val latestVersion: String? = null,
        val downloadUrl: String? = null,
        val changelog: String? = null,
        val error: String? = null
    )
    
    fun checkUpdateAsync(): CompletableFuture<UpdateInfo> {
        return CompletableFuture.supplyAsync {
            try {
                Ohc_login.logger.info("正在检查更新...")
                
                val request = HttpRequest.newBuilder()
                    .uri(URI.create(VERSION_URL))
                    .GET()
                    .timeout(Duration.ofSeconds(10))
                    .build()
                
                val response = httpClient.send(request, HttpResponse.BodyHandlers.ofString())
                
                if (response.statusCode() != 200) {
                    return@supplyAsync UpdateInfo(
                        hasUpdate = false,
                        currentVersion = CURRENT_VERSION,
                        error = "请求失败: ${response.statusCode()}"
                    )
                }
                
                val json = gson.fromJson(response.body(), JsonObject::class.java)
                val mcVersionInfo = json.getAsJsonObject(MC_VERSION)
                
                if (mcVersionInfo == null) {
                    return@supplyAsync UpdateInfo(
                        hasUpdate = false,
                        currentVersion = CURRENT_VERSION,
                        error = "暂无 MC $MC_VERSION 的版本信息"
                    )
                }
                
                val latestVersion = mcVersionInfo.get("latest")?.asString ?: CURRENT_VERSION
                val downloadUrl = mcVersionInfo.get("download")?.asString
                val changelog = mcVersionInfo.get("changelog")?.asString
                
                val hasUpdate = compareVersions(latestVersion, CURRENT_VERSION) > 0
                
                UpdateInfo(
                    hasUpdate = hasUpdate,
                    currentVersion = CURRENT_VERSION,
                    latestVersion = latestVersion,
                    downloadUrl = downloadUrl,
                    changelog = changelog
                )
            } catch (e: Exception) {
                Ohc_login.logger.error("检查更新失败: ${e.message}")
                UpdateInfo(
                    hasUpdate = false,
                    currentVersion = CURRENT_VERSION,
                    error = "网络错误: ${e.message}"
                )
            }
        }.thenApply { info ->
            cachedUpdateInfo = info
            info
        }
    }
    
    private fun compareVersions(v1: String, v2: String): Int {
        val p1 = v1.removePrefix("v").split(".").map { it.toIntOrNull() ?: 0 }
        val p2 = v2.removePrefix("v").split(".").map { it.toIntOrNull() ?: 0 }
        for (i in 0 until maxOf(p1.size, p2.size)) {
            val diff = (p1.getOrElse(i) { 0 }) - (p2.getOrElse(i) { 0 })
            if (diff != 0) return diff
        }
        return 0
    }
}
